package com.gdut.simple.common;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

import com.gdut.simple.data.entity.PhotoFolder;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class PhotoUtils {

    public static List<PhotoFolder> getPhotoes(Context context) {
        Uri photoUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(photoUri, null,
                MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?",
                new String[]{"image/jpeg", "image/png"},
                MediaStore.Images.Media.DATE_MODIFIED);
        String firstImage = null;
        List<PhotoFolder> photoFolders = null;
        HashSet<String> dirPathSet = new HashSet<>();
        if (cursor != null) {
            photoFolders = new ArrayList<>();
            while (cursor.moveToNext()) {
                String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
                if (firstImage == null) {
                    firstImage = path;
                }
                File parentFile = new File(path).getParentFile();
                if (parentFile == null) {
                    continue;
                }
                String dirPath = parentFile.getAbsolutePath();
                PhotoFolder photoFolder = null;
                if (dirPathSet.contains(dirPath)) {
                    continue;
                } else {
                    dirPathSet.add(dirPath);
                    photoFolder = new PhotoFolder();
                    photoFolder.setDir(dirPath);
                    photoFolder.setFirstPhotoPath(path);
                }
                if (parentFile.list() == null) {
                    continue;
                }
                int photoSize = parentFile.list(new FilenameFilter() {
                    @Override
                    public boolean accept(File file, String fileName) {
                        return fileName.endsWith(".jpg") || fileName.endsWith(".png") || fileName.endsWith(".jpeg");
                    }
                }).length;
                photoFolder.setCount(photoSize);
                photoFolders.add(photoFolder);
            }
            Log.i("PhotoUtils", "photoFolders.size() = " + photoFolders.size());
            cursor.close();
            dirPathSet = null;
        }
        return photoFolders;
    }

}
